var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var compression = require('compression');
var logger = require('morgan');
var rfs = require('rotating-file-stream');
var fs = require('fs');
var path = require('path');
var setting = require('./config/setting');
const mongoose = require('./config/db').mongoose;
const transport = require('./config/nodeMail');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var postRouter = require('./routes/post');

var app = express();

var logDirectory = path.join(__dirname, 'log');

// ensure log directory exists
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);

// create a rotating write stream
var accessLogStream = rfs('access.log', {
    interval: '1d', // rotate daily
    path: logDirectory
});

app.locals.name = 'Wayn';
app.locals.getRowArr = function(length, num) {
    let rowNum = Math.ceil(length / num);
    let arr = [];
    for (let i = 0; i < rowNum; i++) {
        let colArr = [];
        if (i >= rowNum - 1) {
            let muNum = length % num == 0 ? num : length % num;
            let index = 0;
            while (muNum-- > 0) {
                colArr.push(i * num + index);
                index++;
            }
        } else {
            let muNum = num;
            let index = 0;
            while (muNum-- > 0) {
                colArr.push(i * num + index);
                index++;
            }
        }
        arr.push(colArr);
    }
    console.log(arr);
    return arr;
};
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
var expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour
//var expiryDate = new Date(Date.now() + expiryDate); // 1 hour
// express-session
app.use(
    session({
        secret: setting.cookieSecret,
        cookie: { httpOnly: true, expires: expiryDate },
        store: new MongoStore({ mongooseConnection: mongoose.connection }),
        saveUninitialized: false,
        resave: false
    })
);
// 响应开启gzip压缩
app.use(compression());
// 日志记录
app.use(
    logger(
        function(tokens, req, res) {
            return [
                tokens['remote-addr'](req, res),
                tokens.date(req, res, 'clf'),
                tokens.method(req, res),
                tokens.url(req, res),
                tokens.status(req, res),
                tokens['user-agent'](req, res),
                tokens.res(req, res, 'content-length'),
                '-',
                tokens['response-time'](req, res),
                'ms'
            ].join(' ');
        },
        {
            stream: accessLogStream,
            skip: function(req, res) {
                return req.url.indexOf('.') > -1;
            }
        }
    )
); //生产日志显示
app.use(logger('dev')); //开发日志显示
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/user', usersRouter);
app.use('/post', postRouter);
app.use(function(req, res, next) {
    next(createError.NotFound());
});
// catch 404 and forward to error handler

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});
//未被express捕获的异常处理
if (process.env.NODE_ENV === 'production') {
    // [2]
    process.on('uncaughtException', function(er) {
        console.error(er.stack); // [3]
        transport.sendMail(
            {
                from: '1669738430@qq.com',
                to: '1669738430@qq.com',
                subject: er.message,
                text: er.stack // [4]
            },
            function(er) {
                if (er) console.error(er);
                process.exit(1); // [5]
            }
        );
    });
}

module.exports = app;
